'use strict';
const loki = require('lokijs');
const lokiApi = (dbFile,callback) => {
  const db = new loki(dbFile, {
      env: 'NODEJS',
      autoload: true,
      autosave : true,
      autosaveInterval : 1000,
      autoloadCallback : loadHandler
    }
  );

  var mycollection = null;
  function loadHandler() {
    console.log('数据库'+dbFile+'加载完成');
    mycollection = db.getCollection('entities');
    if (mycollection === null) {
      mycollection = db.addCollection('entities');
    }
    callback && callback(mycollection,db);
  }

  return {
    chain : function () {
      return mycollection.chain();
    },
    find : function (query, callback) {
      var doc = mycollection.chain().find(query).simplesort('$loki',true).data();
      callback && callback(null,doc);
    },
    insert : function (query, callback) {
      var doc = mycollection.insert(query);
      db.saveDatabase();
      callback && callback(null,doc);
    },
    findOne : function (query, callback) {
      var doc = mycollection.findOne(query);
      callback(null,doc);
    },
    findAndUpdate : function (query, options, callback) {
      var res;
      var doc = mycollection.findAndUpdate(function (obj) {
        return obj.$loki == query.$loki;
      },function (obj) {
        res = Object.assign(obj,options);
        return res;
      });
      db.saveDatabase();
      callback && callback(null,res);
    },
    findAndRemove : function (query, callback) {
      var doc = mycollection.chain().find(query).remove();
      db.saveDatabase();
      callback && callback(null,doc);
    },
    clear : function () {
      return mycollection.clear({
        removeIndices : true
      });
    }
  }
}

// module.exports = lokiApi;